package com.sweet.lb;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Component
@Slf4j
public class LoadBalancerImpl implements LoadBalancer {

    private AtomicInteger atomicInteger = new AtomicInteger(0);

    @Override
    public ServiceInstance getInstanceFromInstances(List<ServiceInstance> serviceInstance) {
        int index = getAndIncrement() % (serviceInstance.size());
        return serviceInstance.get(index);
    }

    /**
     * 获取第几次访问服务
     *
     * @return int
     */
    private final int getAndIncrement() {
        int current;
        int next;
        do {
            current = atomicInteger.get();
            next = current >= 2147483647 ? 0 : current + 1;
            //第一个参数是期望值，第二个参数是修改值
        } while (!atomicInteger.compareAndSet(current, next));
        log.info("It`s {} time to request service ", next);
        return next;
    }
}
